<template>
  <div>
    <page-container title="更换头像">
      <template #form>
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="handleAvatarSuccess"
          :auto-upload="false"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon
            v-else
            class="avatar-uploader-icon"
            :size="40"
            color="#dcdfe6">
            <Plus />
          </el-icon>
        </el-upload>
        <el-button plain @click="uploadRef.$el.querySelector('input').click()">
          <template #icon>
            <Plus />
          </template>
          选择图片</el-button
        >
        <el-button
          :icon="Upload"
          style="background-color: #1c332a; color: #fff"
          @click="uploadHandle"
          >图片上传</el-button
        >
      </template>
    </page-container>
  </div>
</template>
<script setup>
import { Plus, Upload } from '@element-plus/icons-vue';
import { ref } from 'vue';
const uploadRef = ref(null);
// pinia中数据
import { useUserStore } from '@/stores/user.js';
const userStore = useUserStore();
console.log(userStore.user.user_pic, 'userStore');
const imageUrl = ref(userStore.user.user_pic);
const handleAvatarSuccess = (file) => {
  // base64格式
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = function (e) {
    imageUrl.value = e.target.result;
  };
};
import { updateUserAvatarApi } from '@/api/user.js';

const uploadHandle = async () => {
  const res = await updateUserAvatarApi(imageUrl.value);
  console.log(res, '上传成功');
  await userStore.getUser();
  ElMessage.success(res.message);
};
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.size / 1024 / 1024, '上传前');
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式要求为 jpeg/png/jpg');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('图片不能超过20MB!');
    return false;
  }
  return true;
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 228px;
  height: 228px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin-bottom: 20px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 228px;
  height: 228px;
  text-align: center;
}
</style>
